package cn.edu.shu.wechat.webservice.api;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.edu.shu.wechat.core.bean.MessageTypeEnum;
import cn.edu.shu.wechat.core.bean.TextMessage;
import cn.edu.shu.wechat.core.request.bean.WechatRequest;
import cn.edu.shu.wechat.core.response.bean.WechatResponse;
import cn.edu.shu.wechat.core.token.MyToken;
import cn.edu.shu.wechat.webservice.process.WechatCoreProcess;
import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.google.gson.JsonObject;

import cn.edu.shu.wechat.core.bean.BaseMessage;
import cn.edu.shu.wechat.core.util.MessageUtil;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/core/dispatcher")
public class CoreDispatcher {
	private static final Logger logger = LoggerFactory.getLogger(CoreDispatcher.class);
	private  String token;
	@RequestMapping("")
	public @ResponseBody String initWechat(@RequestParam String signature, @RequestParam String timestamp,
			@RequestParam String nonce, @RequestParam String echostr) {
		String[] tempArr = { timestamp, nonce, token };
		Arrays.sort(tempArr);
		StringBuffer buffer = new StringBuffer();
		for (String str : tempArr) {
			buffer.append(str);
		}
		String result = DigestUtils.sha1Hex(buffer.toString());
		logger.info("result: " + result);
		logger.info("signature: " + signature);
		if (result.equals(signature)) {
			return echostr;
		}
		return null;
	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody WechatResponse handletMessage(@RequestBody WechatRequest wechatRequest) {
		WechatCoreProcess coreProcess=new WechatCoreProcess(wechatRequest);
		WechatResponse response=coreProcess.execute();
		logger.info(response.toString());
		return response;
	}

	@Autowired
	public void setToken(MyToken myToken) {
		this.token = myToken.getTokenName();
	}
	
}